import {useState,useEffect}from 'react'
import axios from 'axios'
import { notification,Modal } from 'antd'
import {ExclamationCircleOutlined  } from '@ant-design/icons';
const { confirm } = Modal;

function usePublish(publishType){
    const [dataSource, setdataSource] = useState([])
    const {username} = JSON.parse(localStorage.getItem('token'))
    const handlePublish = (id)=>{
        setdataSource(dataSource.filter(data=>data.id!==id))
        axios.patch(`/news/${id}`,{
            publishState:2,
            publishTime:Date.now()
        }).then(res=>{
            notification.info({
                message:'通知',
                description:'您可以到【发布管理/已发布】中查看您的新闻',
                placement:'bottomRight'
            })
        })
    }
    const handleSunset = (id)=>{
        setdataSource(dataSource.filter(data=>data.id!==id))
        axios.patch(`/news/${id}`,{
            publishState:3
        }).then(res=>{
            notification.info({
                message:'通知',
                description:'您可以到【发布管理/已下线】中查看您的新闻',
                placement:'bottomRight'
            })
        })
    }
    const handleDelete = (id)=>{
        confirm({
            title: '你确定要删除此权限吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                setdataSource(dataSource.filter(data=>data.id!==id))
                axios.delete(`/news/${id}`)
            },
            onCancel() {
              console.log('Cancel');
            },
          });
    }
    useEffect(() => {
        axios.get(`/news?author=${username}&publishState=${publishType}&_expand=category`).then(res=>{
        setdataSource(res.data)
        })

        return () => {
        
        }
    }, [username,publishType])
    return {
        dataSource,
        handlePublish,
        handleSunset,
        handleDelete
    }
}
export default usePublish